package com.updesignsz.admin.util.image;





import com.updesignsz.commom.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


public class FileUploadUtil {
    private static SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM");
//    public static final String FILE_UPLOAD_PATH = "/opt/uploads";
    public static final String FILE_UPLOAD_PATH = "D:/opt/uploads";
    public static final String BARCODE_UPLOAD_PATH = "/uploads/barcode/";
    public static final String QRCODE_UPLOAD_PATH = "/uploads/qrcode/";
    public static final String HTTPS = "http://39.108.37.238";


    public static String getRealPath(HttpServletRequest request) {
        String basePath = HTTPS + request.getServerName()
                + request.getContextPath();
        /**构建图片保存的目录**/
        String logoPathDir = getFileUploadPath();
        if (!logoPathDir.startsWith("/")) {
            logoPathDir = "/" + logoPathDir;
        }
        /**得到图片保存目录的真实路径**/
        String uploadPath = logoPathDir;
//        String uploadPath = request.getSession().getServletContext().getRealPath(logoPathDir);

        String dir = getString("dir", request);

        if (!"".equals(dir)) {
            dir = "/" + dir;
        }
        String fullUploadPath = uploadPath + dir + "/";

        return fullUploadPath;
    }

    public static String getUploadsURL(HttpServletRequest request) {
        String basePath = HTTPS;
        /**构建图片保存的目录**/
//        String logoPathDir = getCurrentRelativePath();

//        String uploadUrl = null;
//        if (basePath.endsWith("/") || logoPathDir.startsWith("/")) {
//
//            uploadUrl = basePath + logoPathDir;
//        } else {
//            uploadUrl = basePath + "/" + logoPathDir;
//        }
//
//        String dir = getString("dir", request);
//
//        if (!"".equals(dir)) {
//            dir = "/" + dir;
//        }
//
//        String fullUploadUrl = uploadUrl + dir + "/";

        return basePath;
    }

    public static String getFileUploadPath() {
        String logoPathDir = FILE_UPLOAD_PATH;

        if (!logoPathDir.startsWith("/")) {
            logoPathDir = "/" + logoPathDir;
        }
        return logoPathDir;
    }

    public static String getCurrentRelativePath() {
        String logoPathDir = getFileUploadPath() + "/" + dateformat.format(new Date());

        if (!logoPathDir.startsWith("/")) {
            logoPathDir = "/" + logoPathDir;
        }
        return logoPathDir;
    }

    /**
     * 获取请求参数中的字符，非null
     *
     * @param name
     * @param request
     * @return
     */
    private static String getString(String name, HttpServletRequest request) {
        String method = request.getMethod();
        name = StringUtil.toString(request.getParameter(name));
        if ("GET".equalsIgnoreCase(method)) {
            try {
                name = new String(name.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {

            }
        }
        return name;
    }

    /**
     * 获取条形码的真实路径
     * @param request
     * @return
     */
    public static String getBarcodeRealPath(HttpServletRequest request) {

        /**构建条形码保存的目录**/
        String logoPathDir = getBarcodeUploadPath();

        /**得到条形码保存目录的真实路径**/
        String uploadPath = request.getSession().getServletContext().getRealPath(logoPathDir);

        //判断文件夹是否存在,不存在就创建
        File fileWJ = new File(uploadPath);
        //如果文件夹不存在则创建
        if (!fileWJ.exists() && !fileWJ.isDirectory()) {
            fileWJ.mkdirs();
        }

        return uploadPath;
    }


    public static String getBarcodeUploadPath() {
        String logoPathDir = BARCODE_UPLOAD_PATH;

        if (!logoPathDir.startsWith("/")) {
            logoPathDir = "/" + logoPathDir;
        }
        return logoPathDir;
    }

    /**
     * 获取二维码的真实路径
     * @param request
     * @return
     */
    public static String getQRcodeRealPath(HttpServletRequest request) {

        /**构建二维码保存的目录**/
        String logoPathDir = getQRcodeUploadPath();

        /**得到条形码保存目录的真实路径**/
        String uploadPath = request.getSession().getServletContext().getRealPath(logoPathDir);

        //判断文件夹是否存在,不存在就创建
        File fileWJ = new File(uploadPath);
        //如果文件夹不存在则创建
        if (!fileWJ.exists() && !fileWJ.isDirectory()) {
            fileWJ.mkdirs();
        }

        return uploadPath;
    }

    public static String getQRcodeUploadPath() {
        String logoPathDir = QRCODE_UPLOAD_PATH;

        if (!logoPathDir.startsWith("/")) {
            logoPathDir = "/" + logoPathDir;
        }
        return logoPathDir;
    }


    public static String download(String urlString, HttpServletRequest request) throws Exception {
        // 创建文件夹
        String uploadPath = FileUploadUtil.getRealPath(request);
        FileUtil.createFileDir(uploadPath);
        //this.url = UUID.randomUUID().toString() + imgFilePath.substring(imgFilePath.lastIndexOf(".")).toLowerCase();
        String fileName = UUID.randomUUID().toString() + ".jpg";
        String fullFileName = uploadPath + fileName;

        // 生成图片
        OutputStream out = new FileOutputStream(fullFileName);
        out.write(getImageFromNetByUrl(urlString));
        out.flush();
        out.close();
        return FileUploadUtil.getUploadsURL(request) + fileName;
    }

    /**
     * 根据地址获得数据的字节流
     * @param strUrl 网络连接地址
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl){
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }
}
